package com.bckj.fastboot.core.extra.license;

import com.bckj.fastboot.core.lang.exception.BusinessException;
import de.schlichtherle.license.*;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * License校验类
 */
@Slf4j
@RequiredArgsConstructor
public class LicenseVerifyServiceImpl implements LicenseVerifyService {

    private final CustomLicenseManager licenseManager;

    @PostConstruct
    public void init() {
        log.info("++++++++ 开始安装证书 ++++++++");
        // 安装证书
        install();
        // 验证证书
        if (!verify()) {
            throw new BusinessException("证书校验失败");
        }
        log.info("++++++++ 证书安装和校验成功 ++++++++");
    }

    /**
     * 安装License证书
     */
    public void install() {
        try {
            // 使用自定义的LicenseManager
            licenseManager.uninstall(); // 先卸载已安装的证书
            licenseManager.install();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    /**
     * 校验License证书
     */
    @Override
    public boolean verify() {
        try {
            LicenseContent licenseContent = licenseManager.verify();
            log.info("证书校验通过，证书有效期：{} - {}",
                    licenseContent.getNotBefore(), licenseContent.getNotAfter());
            return true;
        } catch (Exception e) {
            log.error("证书校验失败：{}", e.getMessage());
            return false;
        }
    }

}